<template>
  <view :class="theme">
    <uv-image width="100%" height="440" src="/static/img/header-promotion.png" />
    <view class="items-center m-30">
      <view class="relative">
        <uv-image radius="30" width="388" height="686" :src="poster.invite_poster?.[0]" />
        <view class="absolute bottom-30 left-50% items-center" style="transform: translateX(-50%);">
          <label class="b-rounded-20 bg-[rgba(1,1,1,0.6)] mb-20 justify-center text-22 w-200 h-40">
            邀请码: {{ poster.invite_code }}
          </label>
          <view v-if="poster.invite_code">
            <l-painter :css="`width: 140rpx; height: 140rpx; background-color: #fff; border-radius: 16rpx;`"
              isCanvasToTempFilePath>
              <l-painter-qrcode css="width: 120rpx; height: 120rpx; margin: 10rpx;" :text="qrCodeText" />
            </l-painter>
          </view>
          <text class="b-rounded-20 text-center text-22 w-full lh-50">
            扫码注册
          </text>
        </view>
      </view>

      <view class="mt-40">
        <uv-image width="500" height="126" src="/static/img/promotion-bottom.png" />
      </view>
      <label @click="uniCopyText({ data: poster.invite_code || '-' })" class="mt-50">
        <text class="text-36 fw-bold mr-12">邀请码: {{ poster.invite_code || "-" }}</text>
        <uv-icon size="32" name="/static/img/icon-copy.png" />
      </label>
    </view>
    <button @click="saveImage" hover-class="op-[0.6]"
      class="bg-5 text-36 color-15 fw-700 b-rounded-50 lh-100 m-30">保存海報</button>

    <l-painter ref="painter" useCORS custom-style="position: fixed; top: 0; left: -100%;" />
    <!-- <l-painter ref="painter" useCORS /> -->
  </view>
</template>

<script lang="ts" setup>
import { useMapState } from "@/common/libs/store";
import { debounce, getClient, uniCopyText } from "@/common/libs/utils";
import { onLoad } from "@dcloudio/uni-app";
import { ref, reactive, computed } from "vue";

const { theme } = useMapState(["theme"]);
const { $config = {} } = getApp().globalData || {};
const poster = reactive<AnyObject>({});
const painter = ref<any>(null);

const qrCodeText = computed(
  () => `${$config.URL_ASSETS + $config.ROUTE_PREFIX}?timestamp=${Date.now()}#/pages/client/auth/register?code=${poster.invite_code || '-'}`
);

onLoad(() => {
  uni.request({
    url: "/invitePoster",
    success({ data }: AnyObject) {
      Object.assign(poster, data);
    }
  });
});

const saveImage = debounce(async () => {
  await renderPoster();
  uni.showToast({ mask: true, icon: "loading" });
  painter.value.canvasToTempFilePath({
    fileType: "png",
    quality: 100,
    success: ({ tempFilePath }: any) => {
      switch (getClient()) {
        case 1:
        case 2:
        case 3:
        case 4:
          const arr = tempFilePath.split(',');
          const bytes = window.atob(arr[1]);
          const ab = new ArrayBuffer(bytes.length);
          const ia = new Uint8Array(ab);
          for (let i = 0; i < bytes.length; i++) {
            ia[i] = bytes.charCodeAt(i);
          }
          const blob = new Blob([ab], { type: `application/octet-stream` });
          const url = URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = `poster.png`;
          a.click();
          URL.revokeObjectURL(url);
          break;
        case 5:
        case 6:
        case 7:
        case 8:
          uni.showToast({ mask: true, icon: "loading" });
          uni.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success: res => {
              uni.showToast({ title: "图片已保存至相册", icon: "none" });
            }
          });
          break;
        case 9:
          // uni.showToast({ title: "图片已保存至相册", icon: "none" });
          break;
        case 10:
          // uni.showToast({ title: "图片已保存至相册", icon: "none" });
          break;
        default:
          break;
      }
      uni.hideToast();
    }
  });
});

const renderPoster = async () => {
  uni.showToast({ mask: true, icon: "loading" });
  await painter.value.render({
    css: {
      width: "388rpx",
      height: "686rpx",
      position: 'relative'
    },
    views: [
      {
        type: 'image',
        css: {
          width: "100%",
          height: "686rpx",
          objectFit: "cover",
          borderRadius: "30rpx",
        },
        src: $config.URL_REMOTE_ASSETS + "/" + poster.invite_poster?.[0]
      },
      {
        type: "view",
        css: {
          position: 'absolute',
          bottom: '30rpx',
          left: '50%',
          marginLeft: '-100rpx',
          width: '200rpx'
        },
        views: [
          {
            type: "text",
            text: `邀请码: ${poster.invite_code}`,
            css: {
              borderRadius: '20rpx',
              backgroundColor: 'rgba(1,1,1,0.6)',
              marginBottom: '20rpx',
              color: '#fff',
              textAlign: 'center',
              fontSize: '22rpx',
              height: '40rpx',
              width: '200rpx'
            }
          },
          {
            type: "view",
            css: {
              width: '140rpx',
              height: '140rpx',
              backgroundColor: '#fff',
              borderRadius: '16rpx',
              marginLeft: '30rpx',
            },
            views: [
              {
                type: "qrcode",
                text: qrCodeText.value,
                css: {
                  width: '120rpx',
                  height: '120rpx',
                  margin: '10rpx',
                }
              }
            ]
          },
          {
            type: "text",
            text: `扫码注册`,
            css: {
              marginTop: '10rpx',
              color: '#fff',
              textAlign: 'center',
              fontSize: '22rpx',
              width: '100%',
              lineHeight: '40rpx'
            }
          },
        ]
      },

    ]
  });
  uni.hideToast();
}

</script>

<style lang="scss" scoped>
// scss
page {
  background: #000;
}
</style>